package com.jd.org.service.impl;


import com.jd.basic.config.BusinessException;
import com.jd.basic.service.impl.BaseServiceImpl;
import com.jd.basic.util.BaiduAuditUtils;
import com.jd.basic.util.MD5Utils;
import com.jd.basic.util.StrUtils;
import com.jd.org.domain.Employee;
import com.jd.org.domain.Shop;
import com.jd.org.domain.ShopAuditLog;

import com.jd.org.mapper.EmployeeMapper;
import com.jd.org.mapper.ShopAuditLogMapper;
import com.jd.org.mapper.ShopMapper;
import com.jd.org.service.IShopService;
import com.jd.system.dto.ShopDto;
import com.jd.user.domain.Logininfo;
import com.jd.user.mapper.LogininfoMapper;
import com.mysql.jdbc.log.Log;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.security.acl.LastOwnerException;
import java.util.List;



/**
 * 业务实现类：员工
 */
@Service
public class ShopServiceImpl extends BaseServiceImpl<Shop> implements IShopService {
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private ShopAuditLogMapper shopAuditLogMapper;
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private JavaMailSender javaMailSender;


    /**
     *
     * 店铺入驻
     * @param shop
     * @throws Exception
     */
    @Override
    public void settlement(Shop shop) throws Exception {
        //一:校验
        //1.1 空值校验 - 前端js校验了后端也要校验,因为前端js校验不安全可以跳过
        String name = shop.getName();
        if (StringUtils.isEmpty(name)){
            throw new BusinessException("店铺名称不能为空!");
        }
        String tel = shop.getTel();
        if (StringUtils.isEmpty(tel)){
            throw new BusinessException("店铺联系电话不能为空!");
        }
        String address = shop.getAddress();
        if (StringUtils.isEmpty(address)){
            throw new BusinessException("店铺地址不能为空!");
        }
        String username = shop.getEmployee().getUsername();
        if (StringUtils.isEmpty(username)){
            throw new BusinessException("店长名称不能为空!");
        }
        String phone = shop.getEmployee().getPhone();
        if (StringUtils.isEmpty(phone)){
            throw new BusinessException("店长手机号不能为空!");
        }
        String email = shop.getEmployee().getEmail();
        if (StringUtils.isEmpty(email)){
            throw new BusinessException("店长邮箱不能为空!");
        }
        String password = shop.getEmployee().getPassword();
        if (StringUtils.isEmpty(password)){
            throw new BusinessException("店长密码不能为空!");
        }
        //2.密码是否一致;不做,如果要做在t_employee加一个字段comfirmPassword即可

        //3.名字是否合规
        if(!BaiduAuditUtils.TextCensor(shop.getName())){
            throw new Exception("店铺名称不合法，请重新输入！");
        }

        //4.是否曾经入驻过
        Shop shopTmp = shopMapper.loadByMessage(shop);
        if (shopTmp != null){
            throw new BusinessException("已入驻,请直接登录。忘记密码请联系管理员!!!");
        }
        //二:入驻业务 - 添加到数据库
        //1.添加到t_employee
        Employee employee = shop.getEmployee();
        //设置盐值以及加密后的密码
        String salt = StrUtils.getComplexRandomString(32);
        employee.setSalt(salt);
        String md5Password = MD5Utils.encrypByMd5(employee.getPassword() + salt);
        employee.setPassword(md5Password);
        //保存logininfo
        Logininfo logininfo = employee2Logininfo(employee);
        logininfoMapper.save(logininfo);
        //保存员工信息
        employee.setLogininfo_id(logininfo.getId());
        employeeMapper.save(employee);

        //2.添加t_shop
        shop.setAdmin_id(employee.getId());
        shopMapper.save(shop);

        //3.修改t_employee的shop_id
        employee.setShop_id(shop.getId());
        employeeMapper.update(employee);


    }

    private Logininfo employee2Logininfo(Employee employee) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(employee, logininfo);
        //设置employee权限为管理员 type = 0
        logininfo.setType(0);
        return logininfo;
    }

    @Transactional
    @Override
    public void pass(ShopAuditLog log) throws MessagingException {
        //1.修改状态：state = 2
        Shop shop = shopMapper.loadById(log.getShopId());
        System.out.println(shop);
        shop.setState(2);
        shopMapper.update(shop);

        //2.添加审核日志到数据库
        log.setState(2);
        log.setAuditId(325L);
        shopAuditLogMapper.save(log);

        //3.发送邮件：审核通过邮件 - 叫他激活
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"UTF-8");
        //设置发送方
        helper.setFrom("461561986@qq.com");
        //设置主题
        helper.setSubject("店铺激活邮件");
        //设置内容
        helper.setText("<h1>你的店铺已经注册!!!</h1>" +
                "<img src='http://123.207.27.208"+shop.getLogo()+"' >" +
                "<a href='http://localhost:8080/shop/active/"+shop.getId()+"'>点击该链接激活</a>",true);
        //设置收件人
        Employee employee = employeeMapper.loadById(shop.getAdmin_id());
        //helper.setTo(employee.getEmail());
        helper.setTo("2335318805@qq.com");
        //发送
        javaMailSender.send(mimeMessage);

    }


    @Transactional
    @Override
    public void reject(ShopAuditLog log) throws MessagingException {
        Shop shop = shopMapper.loadById(log.getShopId());

        //2.添加审核日志到数据库
        log.setState(4);
        log.setAuditId(325L);
        shopAuditLogMapper.save(log);


        //3.发送邮件：驳回邮件 - 告诉他审核失败，重新入驻
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"UTF-8");
        //设置发送方
        helper.setFrom("461561986@qq.com");
        //设置主题
        helper.setSubject("入驻失败邮件");
        //设置内容
        helper.setText("<h1>入驻失败!!!</h1>" +
                "<a href='http://localhost:8081/#/register'>点击重新入驻</a>",true);
        //设置收件人
        Employee employee = employeeMapper.loadById(shop.getAdmin_id());
        //以后都是发送给店铺入驻时填写的邮箱
        //helper.setTo(employee.getEmail());
        helper.setTo("2335318805@qq.com");
        //发送
        javaMailSender.send(mimeMessage);

        //4.删除入驻信息
        //删除管理员信息
        employeeMapper.remove(shop.getAdmin_id());
        //删除店铺信息
        shopMapper.remove(shop.getId());
    }

    @Override
    public List<ShopDto> getShopState() {
        return shopMapper.getShopState();
    }
}
